package mybatis.redis.custom;

import mybatis.redis.RedisCache;
import mybatis.redis.RedisCallback;
import redis.clients.jedis.Jedis;

/**
 * 自定义覆盖官网的缓存,用来满足自己使用自定义mapper的缓存命中和清空
 * @author : zhuqiang
 * @version : V1.0
 * @date : 2016/3/13 11:15
 */
public class MyRedisCache extends RedisCache{
    private final String suffix_CuMapper = "CuMapper";
    private final String suffix_Mapper = "Mapper";
    public MyRedisCache(String id) {
        super(id);
    }

    @Override
    public void clear() {
        final String id = getId();
        boolean isCuMapper = id.endsWith(suffix_CuMapper);
        if(isCuMapper){
            int beginIndex = id.lastIndexOf(".");
            String _id_1 = id.substring(0, beginIndex-2);
            String _id_2 = id.substring(beginIndex, id.length());
            String _id_3 = _id_2.substring(0, _id_2.lastIndexOf(suffix_CuMapper)) + suffix_Mapper;
            final String _id =  _id_1 + _id_3;
            execute(new RedisCallback() {
                @Override
                public Object doWithRedis(Jedis jedis) {
                    jedis.del(_id.toString());
                    return null;
                }
            });
        }else{
            int beginIndex = id.lastIndexOf(".");
            String _id_1 = id.substring(0, beginIndex) + "cu";
            String _id_2 = id.substring(beginIndex, id.lastIndexOf(suffix_Mapper)) + suffix_CuMapper;
            final String _id = _id_1 + _id_2;
            execute(new RedisCallback() {
                @Override
                public Object doWithRedis(Jedis jedis) {
                    jedis.del(_id.toString());
                    return null;
                }
            });
        }

        execute(new RedisCallback() {
            @Override
            public Object doWithRedis(Jedis jedis) {
                jedis.del(id.toString());
                return null;
            }
        });
    }
    private Object execute(RedisCallback callback) {
        Jedis jedis = getPool().getResource();
        try {
            return callback.doWithRedis(jedis);
        } finally {
            jedis.close();
        }
    }
}
